﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;

namespace CacheAttribute.Utils
{
    /// <summary>
    /// 另一种缓存实现方式MemoryCache
    /// </summary>
    public class MemoryCacheUtil : ICacheable
    {
        private readonly IMemoryCache _cache;

        //MemoryCache居然没有Exist
        public bool Exist(string Key)
        {
            object res = _cache.Get(Key);
            return res == null ? false : true;
        }

        public T Get<T>(string key)
        {
            return _cache.Get<T>(key);
        }

        public object Get(string key)
        {
            return _cache.Get(key);
        }

        public bool Remove(string Key)
        {
            try
            {
                _cache.Remove(Key);
                return true;
            }catch(Exception e)
            {
                return false;
            }
        }

        public bool RemovePattern(string Pattern)
        {
            try
            {
                _cache.Remove(Pattern);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public bool Set(string key, object obj, int Expire = 1800)
        {
            object res = _cache.Set<object>(key, obj,DateTimeOffset.FromUnixTimeSeconds(Expire));
            return res == null ? false : true;
        }
    }
}
